package com.ktjiaoyu.controller;


import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import com.oracle.wls.shaded.org.apache.xpath.operations.Mod;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    @Qualifier("toLocalUploadService")  //指定注入保存到本地硬盘的上传业务实现对象
    private UploadService uploadService;

//    @GetMapping("/accountExist")
//    @ResponseBody
//    public Map<String, Object> checkAccountExist(@RequestParam String account) {
//        Map<String, Object> result = new HashMap<>();
//        try {
//            SysUser user = sysUserService.findByAccount(account);
//            result.put("exist", user != null ? 1 : 0);
//        } catch (Exception e) {
//            result.put("error", "验证账号时发生错误");
//            logger.error("验证账号出错", e);
//        }
//        return result;
//    }

    @RequestMapping("/page")
    public String page(Model model, SysUser condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<SysUser> page = null;
        try {
            //查询用户分页数据
            page = sysUserService.findPage(condition, pageNo, pageSize);
            //查询所有角色的信息
            List<SysRole> roleList = sysRoleService.findAll();
            //将分页的数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("roleList", roleList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            logger.error("SysUserController中的page方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    //跳转到save.jsp页面
    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            roleList = sysRoleService.findAll();
            //有角色下拉框需要的数据
            model.addAttribute("roleList", roleList);
            //会显示数据时需要SysUser对象，这里空对象避免错误
            model.addAttribute("sysUser", new SysUser());
        } catch (Exception e) {
            logger.error("SysUserController中的toSave方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    //保存或修改数据接口
    @PostMapping("/save")
    public String save(@ModelAttribute SysUser sysUser,
                       @RequestParam("idPic") MultipartFile idPic,
                       @RequestParam("workPic") MultipartFile workPic) throws Exception {
        //允许上传的图片扩展名
        String[] allowImageExt = new String[]{"png", "jpg", "jpeg", "gif", "bmp"};
        try {
            //上传证件照
            if (!idPic.isEmpty()) {
                String idPicPath = uploadService.uploadFile(idPic, allowImageExt);
                sysUser.setIdPicPath(idPicPath);
            }
            //上传工作照
            if (!workPic.isEmpty()) {
                String workPicPath = uploadService.uploadFile(workPic, allowImageExt);
                sysUser.setWorkPicPath(workPicPath);
            }
            //通过父类的session方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if (sysUser.getId() == null) {
                //保存用户信息
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
            } else {
                //修改用户信息
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
            }
            boolean ok = sysUserService.saveOrUpdate(sysUser);
            if (ok) {
                //保存成功,重定向到列表页面
                return redirect("/main/user/page");
            }

        } catch (Exception e) {
            logger.error("SysUserController中的doSave方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    //查询用户信息并跳转到查看页面
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) {
        SysUser sysUser = null;
        try {
            sysUser = sysUserService.findById(id);
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            logger.error("SysUserController中的view方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "user/view";
    }

    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id) {
        HashMap<String, Object> resultMap = new HashMap<>();
        SysUser info = null;
        try {
            info = sysUserService.findById(id);
            if (info != null){
                resultMap.put("code", 0);
                resultMap.put("data", info);
            }else {
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            logger.error("SysUserController中的view方法执行错误", e);
            resultMap.put("error", "查询用户信息时发生错误");
        }
        return resultMap;
    }

    //查询用户信息并跳转到修改页面
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysUser sysUser = null;
        List<SysRole> roleList = null;
        try {
            sysUser = sysUserService.findById(id);
            roleList = sysRoleService.findAll();
            model.addAttribute("roleList", roleList);
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            logger.error("SysUserController中的edit方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @ResponseBody
    @GetMapping("/accountExist")
    public String accountExist(@RequestParam String account) {
        logger.info("检查用户名是否存在：{}", account);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist", 0);
        }else{
            try{
                SysUser sysUser = sysUserService.findByAccount(account);
                if (sysUser != null){
                    //用户名已存在
                    resultMap.put("exist", 1);
                }else{
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                resultMap.put("error", "验证账号时发生错误");
                logger.error("验证账号出错", e);
            }
        }
        return JSON.toJSONString(resultMap);
    }


    //删除供应商信息
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Map<String, Object> del(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = sysUserService.deleteById(id);
            if (ok){
                result.put("code",200);
                result.put("message", "删除成功");
            }else {
                result.put("code",500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            logger.error("SupplierController中的del方法执行错误", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        return result;
    }

}
